package cn.yj.frame.spring.event;

import cn.yj.frame.netty.NettyServer;
import cn.yj.register.RegisterConfig;
import java.net.InetSocketAddress;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 用于发布RPC对应的服务进行做接口暴露
 *
 * @author 永健
 * @since 2022-01-19 10:23
 */
public class RpcRegisterApplicationListener implements ApplicationListener<ApplicationStartedEvent> {

	@Override
	public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
		ConfigurableApplicationContext context = applicationStartedEvent.getApplicationContext();
		ConfigurableEnvironment env = context.getEnvironment();
		String host = env.getProperty("spring.rpc.provider.host");
		String applicationName = env.getProperty("spring.application.name");
		if ("".equals(host) || host == null) {
			return;
		}
		String[] split = host.split(":");
		InetSocketAddress inetSocketAddress = new InetSocketAddress(split[0], Integer.parseInt(split[1]));
		// 启动netty，提供者服务启动，注册服务
		RegisterConfig.getInstance().register(applicationName, host);
		new NettyServer().start(inetSocketAddress);
	}

}
